import logging
from configparser import ConfigParser
from time import strftime
from loguru import logger

from utils.project_path import ProjectPath


class HandleLog(logging.Handler):
    def emit(self, record):
        logging.getLogger(record.name).handle(record)


class MyLog():
    __instance = None  # 单例
    __call_flag = True

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def get_log(self):
        if self.__call_flag:
            current_date = strftime("%Y%m%d_%H%M%S")
            cfg = ConfigParser()
            cfg.read(ProjectPath.configs_path / 'loguru.ini', encoding='utf-8')
            # logger.remove(handler_id=None)  # 关闭控制台输出
            logger.add(ProjectPath.logs_path / f'autotest_{current_date}.log',
                       level=cfg.get('log', 'level'),
                       format=cfg.get('log', 'format'),
                       rotation=cfg.get('log', 'rotation'),
                       retention=cfg.get('log', 'retention'),
                       compression=cfg.get('log', 'compression'))
            self.__call_flag = False
        return logger


log = MyLog().get_log()

if __name__ == '__main__':
    log.info("这是测试日志")
